import { ref } from 'vue';
import type { ShowSearchType } from 'ant-design-vue/es/cascader';

import { queryProjectTree } from '@/api/list/project-list';
import { queryBuildTree2RoomNoPublic, queryBuildTree2Room } from '@/api/list/build';

import { message } from 'ant-design-vue';
import { isUndefined, isEmpty, isArray } from 'lodash-es';
import { findTree } from 'xe-utils';

const useProject2Room = (props, modelRef) => {
    const treeData = ref<any[]>([]);
    const buildData = ref<any[]>([]);

    const queryTreeData = () => {
        queryProjectTree().then(res => {
            treeData.value = [res.data as any];
            const projectCode = modelRef.projectCode || props.model?.projectCode;
            console.log(projectCode, projectCode.at(-1), isArray(projectCode));

            if (!isUndefined(projectCode)) {
                const project: any = findTree(treeData.value, p => p.code === (isArray(projectCode) ? projectCode.at(-1) : projectCode));
                console.log(project, props.model);

                if (!isUndefined(project.item)) {
                    modelRef.projectCode = project.nodes.map(item => item.code);
                    handleCascaderChange(modelRef.projectCode, project.nodes);
                }
            }
        });
    };

    const handleCascaderChange = (value: any, selectedOptions: any) => {
        console.log(value, selectedOptions);
        buildData.value = [];
        const select = selectedOptions[selectedOptions.length - 1];
        modelRef.projectName = select.name;
        if (select.type === 'dept' && select.children.length === 0) {
            queryBuildTreeData(select);
        }
    };

    const queryBuildTreeData = select => {
        if (!isEmpty(modelRef.properties)) {
            modelRef.properties = [];
        }
        (props.noPublic === false ? queryBuildTree2Room : queryBuildTree2RoomNoPublic)(select.code).then(build => {
            if (!isEmpty(build.data)) {
                buildData.value = build.data;
            } else {
                message.warning('未查询到项目对应的楼栋信息');
                buildData.value = [];
            }
        });
    };

    const filter: ShowSearchType['filter'] = (inputValue, path) => {
        return path.some(option => option.name.toLowerCase().indexOf(inputValue.toLowerCase()) > -1);
    };

    return {
        treeData,
        buildData,
        filter,
        queryTreeData,
        handleCascaderChange,
        queryBuildTreeData,
    };
};

export default useProject2Room;
